package org.jeecg.modules.platformMasterEndPoint.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.jx.constant.FileConstants;
import org.jeecg.modules.platformMasterEndPoint.entity.JxCategoryDo;
import org.jeecg.modules.platformMasterEndPoint.entity.JxCategoryVo;
import org.jeecg.modules.platformMasterEndPoint.service.IJxCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Api(tags = "店铺主品类管理")
@RestController
@RequestMapping("/jx/jxStoreCategory")
@Slf4j
public class JxCategoryController {

    @Autowired
    private IJxCategoryService storeCategoryService;

    /**
     * 接口 4.6 新增或编辑 店铺类别
     * @param categoryVo
     * @return
     */
    @ApiOperation("添加店铺主品类")
    @PostMapping("/addOrEditStoreCategory")
    public Result<?> addOrEditStoreCategory(
            @RequestBody() JxCategoryVo categoryVo) throws Exception {
        if (categoryVo.getCategoryId() != null && !categoryVo.getCategoryId().isEmpty()) {
            JxCategoryDo storeCategoryDo = new JxCategoryDo();
            // 编辑场景

            storeCategoryDo.setCategoryName(categoryVo.getCategoryName());
            if (categoryVo.getImage().trim().startsWith("http")) {
                // 编辑店铺类别信息，且仅修改了名称，没有重新上传图片场景
                storeCategoryDo.setImage(categoryVo.getImage());
            } else {
                // 若重新上传了logo图片，则需要 将logo图片从临时目录移动到 正式目录，并生成url
                String finalImageUrl = moveAndGenerateImageUrl(categoryVo.getImage());
                storeCategoryDo.setImage(finalImageUrl);
            }

            storeCategoryService.updateById(storeCategoryDo);
        } else {
            // 首先判断 需要新增的主品类名是否已经存在
            JxCategoryDo storeCategoryDo1 = storeCategoryService.getOne(new LambdaQueryWrapper<JxCategoryDo>().eq(JxCategoryDo::getCategoryName, categoryVo.getCategoryName()));
            if (storeCategoryDo1 != null) {
                return Result.error("类别 " + categoryVo.getCategoryName() + " 已存在，不能添加重名的类别");
            }

            try {
                // 新增场景，需要将logo图片从临时目录移动到 正式目录，并生成url
                String finalImageUrl = moveAndGenerateImageUrl(categoryVo.getImage());

                JxCategoryDo storeCategoryDo = new JxCategoryDo();
                storeCategoryDo.setCategoryName(categoryVo.getCategoryName());
                storeCategoryDo.setImage(finalImageUrl);
                storeCategoryDo.setCreateTime(new Date());

                storeCategoryService.save(storeCategoryDo);
                log.info("添加店铺主品类成功");
            } catch (Exception ex) {
                log.info("批量添加店铺主品类失败，异常栈如下");
                log.error("", ex);
                return Result.error(ex.getMessage());
            }
        }

        return Result.ok();
    }


    /**
     * 接口4.8 当请求参数不传递 keyword 或者 传递的keyword为 空字符串时，返回所有的主品类
     * @param keyword
     * @return
     */
    @ApiOperation("根据主品类id或名称进行搜索，keyword的可以是id或品类名称")
    @GetMapping("/queryCategoryInfoByKeyword")
    public Result<?> queryCategoryInfoByKeyword(
            @RequestParam(value = "keyword", required = false, defaultValue = "") String keyword) {

        List<JxCategoryDo> list = storeCategoryService.getBaseMapper()
                .selectList(
                        new LambdaQueryWrapper<JxCategoryDo>()
                                .eq(JxCategoryDo::getDelFlag, 0)
                                .and(wrapper -> {
                                    wrapper.like(JxCategoryDo::getCategoryName, keyword).or().like(JxCategoryDo::getId, keyword);
                                }));
        List<HashMap<String, Object>> categoryVos = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size() ; i ++) {
                JxCategoryDo storeCategoryDo = list.get(i);
                HashMap<String,Object> category = new HashMap<>();
                category.put("id", storeCategoryDo.getId());
                category.put("categoryName", storeCategoryDo.getCategoryName());
                category.put("image", storeCategoryDo.getImage());

                categoryVos.add(category);
            }
        }
        return Result.ok(categoryVos);
    }

    /**
     * 接口4.7 删除某个店铺类别
     * @param categoryId
     * @return
     */
    @ApiOperation("根据主品类id删除某个品类")
    @DeleteMapping("deleteCategoryById")
    public Result<?> deleteCategoryById(
            @RequestParam("categoryId") String categoryId) {

        boolean success = storeCategoryService.update(new UpdateWrapper<JxCategoryDo>().set("del_flag", 1).eq("id", categoryId));

        if (success) {
            return Result.ok("删除成功");
        } else {
            return Result.error("删除失败，请联系后台技术人员进行处理");
        }
    }


    /**
     * 将上传到临时目录下的图片，移动到正式目录下，并生成可访问的url
     * @param imageName
     * @return
     * @throws Exception
     */
    private String moveAndGenerateImageUrl(String imageName) throws Exception {

        String finalImageUrl = "";
        File categoryImageUploadDir = new File(Paths.get(FileConstants.IMAGE_FOOD_UPLOAD_DIR , "categories").toUri());
        if (!categoryImageUploadDir.exists()) {
            categoryImageUploadDir.mkdirs();
        }
        if (imageName.trim().startsWith("http")) {
            log.info("调用参数中的图片链接为: {}, 是url，属于编辑店铺类型信息场景，且没有更新图片，不需要重新移动图片，不需要重新生成图片url", imageName);
            finalImageUrl = imageName;
        } else {
            log.info("调用参数中的图片链接为: {},不是url ，需要移动图片，并生成图片url", imageName);
            try {
                Path tempPath =  Paths.get(FileConstants.FILE_UPLOAD_TEMP_DIR , imageName);
                Path imagePath = Paths.get(categoryImageUploadDir.getAbsolutePath(), imageName);
                Files.move(tempPath, imagePath);
                log.info("temp: {}, imagePath: {}", tempPath, imagePath);
                finalImageUrl = FileConstants.IMAGE_URL_BASE + "/categories/" + imageName;
            } catch (IOException e) {
                log.error("录入新店铺类别时，将临时目录下的图片移动到 正式目录失败");
                log.error("{}", e);
                throw new Exception("录入新店铺类别时，将临时目录下的图片移动到 正式目录失败");
            }
        }

        return finalImageUrl;
    }
}
